<template>
    <div class="loginView">
        <div class="loginForm">
            <h2>登录界面</h2>
            <el-form ref="formRule" :rules="rules" label-position="top" label-width="100px" :model="form">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" placeholder="请输入密码" />
                </el-form-item>
                <el-form-item style="margin-top:40px;">
                    <el-button style="width:100%;" type="primary" @click="submitForm(formRule)">登录</el-button>
                </el-form-item>
            </el-form>
        </div>

    </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router';
import axios from 'axios'
const formRule = ref(null);
const router=useRouter();
import { ElMessage } from 'element-plus'
const form = reactive({
    username: '',
    password: ''
})
const submitForm = (formRule) => {
    formRule.validate((valid, fields) => {
        if(valid){
            axios({
                method:"post",
                url:'http://localhost:5000/login',
                data:form
            }).then(res=>{
                if(res.data.code==200){
                    ElMessage({
                        message: '登录成功',
                        type: 'success',
                    })
                    setTimeout(()=>{
                        sessionStorage.setItem("token",res.data.token);
                        sessionStorage.setItem("username",form.username)
                        router.push("/")
                    },500)
                }else{
                    ElMessage({
                        message: res.data.msg,
                        type: 'error',
                    })
                }
            })
        }
    })
}
const rules = reactive({
    username: [{ required: true, message: '请输入名称', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
})
</script>
<style scoped lang="scss">
.loginView {
    width: 100%;
    height: 100vh;
    background: linear-gradient(to right, rgb(104, 104, 235), rgb(198, 198, 231));
    display: flex;
    align-items: center;
    justify-content: center;

    .loginForm {
        width: 360px;
        height: 350px;
        background-color: #ffffff;
        display: flex;
        flex-direction: column;
        text-align: center;

        .el-form {
            margin: 10px 40px;
        }
    }
}
</style>
   